from werkzeug.security import generate_password_hash  # 根据字符串参数进行加密
from werkzeug.security import check_password_hash  # 参数1：加密后数据，参数2：被加密字符串
from flask_jwt_extended import create_access_token
from app.common.constants import ResultCode
from app.user.models import UserModel
from app.user.models import User
from app.ext import r


class UserAuth(User):

    def register(self, data):
        """ 注册操作 """
        user = UserModel()
        return user.insert(data)

    def login(self, data):
        """ 用户登录 """
        friend = User.query.filter_by(user_id=data['user_id']).first()  # 根据username进行查询， 不存在则None
        if friend is None:
            return False
        else:
            if data['user_id'] == friend.user_id and check_password_hash(friend.password, data['password']):
                """
                使用 check_password_hash 根据 数据的加密password进行校验
                登录成功 根据用户的id 生成token 并返回,
                """
                tokens = create_access_token(identity={"user_id": data['user_id']})
                r.set(data['user_id'], tokens, ex=300)  # 存储token
                return {"response": ResultCode.LOGIN_SUCCESS, "token": tokens}
            else:
                return {"response": ResultCode.USERNAME_PASSWORD_INCORRECT, "token": None}
